<template>
  <el-dialog
    :title="isEdit ? '编辑管理员' : '添加管理员'"
    v-model="dialogVisible"
    width="500px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="formData.username"
          placeholder="请输入用户名"
          :disabled="isEdit"
        />
      </el-form-item>
      
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="formData.password"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>
      
      <el-form-item label="角色" prop="role">
        <el-select
          v-model="formData.role"
          placeholder="请选择角色"
          style="width: 100%"
        >
          <el-option label="普通管理员" value="ADMIN" />
          <el-option label="超级管理员" value="SUPER_ADMIN" />
        </el-select>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isEdit ? '更新' : '添加' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { createAdminApi, updateAdminApi } from '@/api/admin/admin'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  adminData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:visible', 'success'])

// 响应式数据
const dialogVisible = ref(false)
const loading = ref(false)
const formRef = ref()

// 表单数据
const formData = reactive({
  username: '',
  password: '',
  role: 'ADMIN'
})

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 监听visible变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    nextTick(() => {
      resetForm()
      if (props.isEdit && props.adminData) {
        Object.assign(formData, {
          username: props.adminData.username || '',
          password: '', // 编辑时不显示密码
          role: props.adminData.role || 'ADMIN'
        })
      }
    })
  }
})

// 监听dialogVisible变化
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

// 方法
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    username: '',
    password: '',
    role: 'ADMIN'
  })
}

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    loading.value = true
    
    let response
    if (props.isEdit) {
      response = await updateAdminApi(props.adminData.id, formData)
    } else {
      response = await createAdminApi(formData)
    }
    
    if (response.code === 200) {
      ElMessage.success(response.message || `${props.isEdit ? '更新' : '添加'}成功`)
      emit('success')
      handleClose()
    } else {
      ElMessage.error(response.message || `${props.isEdit ? '更新' : '添加'}失败`)
    }
  } catch (error) {
    if (error !== 'validation failed') {
      console.error(`${props.isEdit ? '更新' : '添加'}管理员失败:`, error)
      ElMessage.error(`${props.isEdit ? '更新' : '添加'}管理员失败`)
    }
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
